import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/admin/users/Users.vue'
import Add from '../components/admin/users/Add.vue'
import Articles from '../components/admin/articles/Articles.vue'
import addArticle from '../components/admin/articles/addArticle.vue'
import Student from '../components/admin/students/Student'
import StuNotSelect from '../components/admin/students/StuNotSelect.vue'
import StuSelected from '../components/admin/students/StuSelected.vue'
import teacherArticle from '../components/teacher/teacherArticle.vue'
import Select from '../components/student/Select.vue'
import Comment from '../components/admin/comment/Comment.vue'
import sComment from '../components/student/sComment.vue'
import Center from '../components/center/Center.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/home',
    component: Home, 
    children: [
      { path: '/home', redirect: '/welcome' },
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/users/add', component: Add },
      { path: '/articles', component: Articles },
      { path: '/articles/add', component: addArticle },
      { path: '/students', component: Student },
      { path: '/students/not', component: StuNotSelect },
      { path: '/students/true', component: StuSelected },
      { path: '/teacher/articles', component: teacherArticle },
      // 教师端添加题目与管理员端添加题目共用一个组件
      { path: '/teacher/articles/add', component: addArticle },
      { path: '/student/select', component: Select },
      // 评论管理路由
      { path: '/comment', component: Comment },
      // 学生端评论路由
      { path: '/sComment', component: sComment },
      // 个人中心
      { path: '/center', component: Center }
    ] }
]

const router = new VueRouter({
  routes
})

// 挂载路由防卫导航守卫
router.beforeEach((to, from, next) => {
  // to 表示将要访问的地址 from 表示来自的地址， next表示放行
  if (to.path === '/login') return next()
  // 获取localStorage里面的token
  const tokenStr = window.localStorage.getItem('token')
  // 如果获取不到，终止向下执行并强制跳转到/login
  if (!tokenStr) return next('/login')
  next()
})

export default router
